package handlers

import (
	"bird-novel/cache"
	"bird-novel/models"
	"bird-novel/pgk"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户名密码不能为空",
		})
		return
	}
	redis_data_key := "login_" + username
	errcount, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Int()
	if errcount >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pgk.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_data_key)
		if errcount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_data_key, 3, time.Hour*2)
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func List(c *gin.Context) {
	var novel []models.Novel
	redis_data_key := "novel_list"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Result()
	if redisData == "" {
		models.DB.Find(&novel)
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_data_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &novel)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": novel,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var novel models.Novel
	models.DB.First(&novel, id)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": novel,
	})
	return
}
